<?php

namespace Library;
use Think\Log;

/**
 * 中奖订单处理类, 后期将所有Prizes 中的订单处理移到此类中
 *
 * @author pufan
 */
class PrizesOrder {
    protected $prizes_order_model;

    public function __construct() {
        $this->prizes_order_model = D('prizes_order');
    }
    
    /*
     * 获取卡券详细信息
     */
    public function getOneCardByUserd($userid) {
        $where['order_status'] = 1;
        $where['userid'] = $userid;
        $userCards = $this->prizes_order_model->Field('card_id, card_num')->where($where)->order('id desc')->find();
        Log::record('userCards:'.json_encode($userCards));
        if (is_array($userCards)) {
            return $userCards;
        }
        return false;
    }
    
    /*
     * 领取卡券
     */
    public function getPrizes($card_list_code, $remark='') {

        try {
            $user = \Library\User::getInstance();
            if ($user) {
                $data['order_status'] = 1;
                $data['send_time'] = date("Y-m-d H:i:s",time());
                if ($remark) {
                    $data['remark'] = $remark;
                }
                $where['openid'] = $user->getCurrentOpenId();
                $where['card_num'] = $card_list_code;
                $where['order_status'] = 0;
                $where['send_time'] =  array('EXP','IS NULL');
                $this->prizes_order_model->where($where)->save($data);
                \Think\Log::record('getPrizes :card_list_code'.$card_list_code);

                return TRUE;
            }
        } catch (\Exception $exc) {
            \Think\Log::record('getPrizes '.$exc->getTraceAsString());
        }
        return FALSE;
    }
    
    public function replaceTmpPrizes() { 
        
        try {
            $user = \Library\User::getInstance();
            if ($user) {
                $data['userid'] = $_SESSION['user_id'];
                $where['openid'] = $_SESSION['open_id'];
                $this->prizes_order_model->where($where)->save($data);
                \Think\Log::record('getPrizes :card_list_code'.$card_list_code);

                return TRUE;
            }
        } catch (\Exception $exc) {
            \Think\Log::record('getPrizes '.$exc->getTraceAsString());
        }
        return FALSE;
    }
}
